package io.gitee.kotle.player.ui.view.exo

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import androidx.media3.common.MediaItem
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import io.gitee.kotle.player.core.IPlayer
import io.gitee.kotle.player.core.impl.exoplayer.IExoPlayerMode

/**
 * 倍速调节的view
 */
class ExoPlayerSpeedView : AppCompatTextView, IExoPlayerView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    )

    private val speedList = mutableListOf(1f, 1.5f, 2f, 3f, 5f)

    override fun onPlayerViewConfigCreated(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigCreated(player, config)
        onSpeedChange(player, player.speed)
        setOnClickListener {
            config.singleTapConfirmed.value = null
            MaterialAlertDialogBuilder(it.context)
                .setTitle("选择倍速")
                .setItems(
                    speedList.map { it.toString() }.toTypedArray(),
                ) { _, which ->
                    player.speed = speedList[which]
                }
                .setCancelable(false)
                .setPositiveButton(android.R.string.cancel, null)
                .setOnDismissListener {
                    config.singleTapConfirmed.value = true
                }
                .show()
        }
    }


    override fun onSpeedChange(player: IPlayer<MediaItem, IExoPlayerMode>, speed: Float) {
        super.onSpeedChange(player, speed)
        text = speed.toString()
    }

    override fun onPlayerViewConfigDestroyed(
        player: IPlayer<MediaItem, IExoPlayerMode>,
        config: ExoPlayerViewConfig<IExoPlayerMode>
    ) {
        super.onPlayerViewConfigDestroyed(player, config)
    }

    override fun needPlayerListener(): Boolean {
        return true
    }

}